<template>
  <div class="announcement-detail-container">
    <div class="page-header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/announcements' }">系统公告</el-breadcrumb-item>
        <el-breadcrumb-item>公告详情</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>
    
    <template v-else>
      <!-- 公告不存在 -->
      <el-empty 
        v-if="!announcement" 
        description="该公告不存在或已被删除" 
        :image-size="200">
        <el-button type="primary" @click="$router.push('/announcements')">返回公告列表</el-button>
      </el-empty>
      
      <!-- 公告详情 -->
      <template v-else>
        <el-card class="detail-card" shadow="hover">
          <div class="announcement-header">
            <h1 class="announcement-title">
              <el-tag 
                v-if="announcement.priority === 2" 
                size="medium" 
                type="danger" 
                effect="dark">紧急</el-tag>
              <el-tag 
                v-else-if="announcement.priority === 1" 
                size="medium"
                type="warning" 
                effect="plain">重要</el-tag>
              <span>{{ announcement.title }}</span>
            </h1>
            <div class="announcement-meta">
              <div class="meta-item">
                <i class="el-icon-user"></i>
                <span>发布者：{{ announcement.publisher_id }}</span>
              </div>
              <div class="meta-item">
                <i class="el-icon-document"></i>
                <span>类型：{{ announcement.type }}</span>
              </div>
              <div class="meta-item">
                <i class="el-icon-view"></i>
                <span>阅读量：{{ announcement.view_count }}</span>
              </div>
              <div class="meta-item">
                <i class="el-icon-time"></i>
                <span>发布时间：{{ formatDateTime(announcement.created_at) }}</span>
              </div>
              <div class="meta-item" v-if="announcement.start_time">
                <i class="el-icon-timer"></i>
                <span>生效时间：{{ formatDateTime(announcement.start_time) }}</span>
              </div>
              <div class="meta-item" v-if="announcement.end_time">
                <i class="el-icon-finished"></i>
                <span>结束时间：{{ formatDateTime(announcement.end_time) }}</span>
              </div>
            </div>
          </div>
          
          <el-divider></el-divider>
          
          <div class="announcement-content">
            <p v-for="(paragraph, index) in contentParagraphs" :key="index" class="content-paragraph">
              {{ paragraph }}
            </p>
          </div>
          
          <div class="announcement-actions">
            <el-button type="primary" @click="$router.push('/announcements')">
              <i class="el-icon-arrow-left"></i> 返回公告列表
            </el-button>
          </div>
        </el-card>
        
        <!-- 相关公告 -->
        <el-card class="related-card" shadow="hover" v-if="relatedAnnouncements.length > 0">
          <div slot="header" class="related-header">
            <i class="el-icon-connection"></i>
            <span>相关公告</span>
          </div>
          
          <div class="related-list">
            <div 
              v-for="item in relatedAnnouncements" 
              :key="item.id" 
              class="related-item"
              @click="viewRelated(item.id)">
              <div class="related-title">
                <el-tag 
                  v-if="item.priority === 2" 
                  size="mini" 
                  type="danger" 
                  effect="dark">紧急</el-tag>
                <el-tag 
                  v-else-if="item.priority === 1" 
                  size="mini"
                  type="warning" 
                  effect="plain">重要</el-tag>
                <span>{{ item.title }}</span>
              </div>
              <div class="related-meta">
                <span><i class="el-icon-document"></i> {{ item.type }}</span>
                <span><i class="el-icon-time"></i> {{ formatDate(item.created_at) }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </template>
    </template>
  </div>
</template>

<script>
import announcementApi from '@/api/announcement';

export default {
  name: 'AnnouncementDetail',
  data() {
    return {
      // 加载状态
      loading: true,
      
      // 公告详情
      announcement: null,
      
      // 相关公告
      relatedAnnouncements: []
    };
  },
  computed: {
    /**
     * 将内容按换行符分割为段落
     */
    contentParagraphs() {
      if (!this.announcement || !this.announcement.content) {
        return [];
      }
      return this.announcement.content.split('\n').filter(paragraph => paragraph.trim());
    },
    
    /**
     * 获取公告ID
     */
    announcementId() {
      return parseInt(this.$route.params.id);
    }
  },
  created() {
    // 获取公告详情
    this.fetchAnnouncementDetail();
  },
  methods: {
    /**
     * 获取公告详情
     */
    fetchAnnouncementDetail() {
      this.loading = true;
      
      announcementApi.getAnnouncementById(this.announcementId)
        .then(response => {
          if (response && response.data) {
            // 处理可能的字段命名差异
            this.announcement = this.formatAnnouncementData(response.data);
            // 获取相关公告
            this.fetchRelatedAnnouncements();
          } else {
            this.announcement = null;
            this.$message.error('获取公告详情失败');
          }
        })
        .catch(error => {
          console.error('获取公告详情出错', error);
          this.$message.error('获取公告详情出错');
          this.announcement = null;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    /**
     * 处理公告数据，确保字段名称一致性
     * @param {Object} data - 后端返回的原始数据
     * @returns {Object} - 标准化后的数据
     */
    formatAnnouncementData(data) {
      console.log('原始公告数据:', data);
      // 复制对象以避免修改原始数据
      return {
        id: data.id || 0,
        title: data.title || '',
        content: data.content || '',
        type: data.type || '其他',
        priority: data.priority || 0,
        publisher_id: data.publisherId || data.publisher_id || '系统',
        view_count: data.viewCount || data.view_count || 0,
        created_at: data.createdAt || data.created_at || data.createdTime || data.createTime || new Date().toISOString(),
        start_time: data.startTime || data.start_time || data.effectiveStartTime || null,
        end_time: data.endTime || data.end_time || data.effectiveEndTime || null,
        updated_at: data.updatedAt || data.updated_at || data.updateTime || data.updatedTime || null
      };
    },
    
    /**
     * 获取相关公告
     */
    fetchRelatedAnnouncements() {
      if (!this.announcement) return;
      
      // 构造查询参数，查询同类型的其他公告
      const params = {
        pageNum: 1,
        pageSize: 5,
        type: this.announcement.type,
        status: 1 // 只查询已发布的公告
      };
      
      announcementApi.getAnnouncements(params)
        .then(response => {
          if (response && response.data && response.data.rows) {
            // 修改这里，使用正确的数据结构路径
            // 后端返回的数据结构是 {code, msg, data: {total, rows}}
            // 过滤掉当前公告
            this.relatedAnnouncements = response.data.rows
              .filter(item => item.id !== this.announcement.id)
              .slice(0, 3); // 最多显示3条
            console.log('获取到的相关公告:', this.relatedAnnouncements);
          }
        })
        .catch(error => {
          console.error('获取相关公告出错', error);
          this.relatedAnnouncements = [];
        });
    },
    
    /**
     * 查看相关公告
     * @param {number} id - 公告ID
     */
    viewRelated(id) {
      // 记录查看次数
      announcementApi.incrementViewCount(id).catch(() => {});
      
      // 跳转到相关公告
      this.$router.push(`/announcements/detail/${id}`);
      
      // 重新获取公告详情
      this.fetchAnnouncementDetail();
      
      // 滚动到顶部
      window.scrollTo(0, 0);
    },
    
    /**
     * 格式化日期时间
     * @param {string} dateStr - 日期字符串
     * @returns {string} - 格式化后的日期时间
     */
    formatDateTime(dateStr) {
      if (!dateStr) return '';
      
      try {
        // 处理多种可能的日期格式
        // 1. 处理包含T和Z的ISO格式
        // 2. 处理普通的日期时间格式 (YYYY-MM-DD HH:MM:SS)
        let date;
        if (typeof dateStr === 'string') {
          // 如果是普通的日期时间字符串格式(不含T)，先标准化为ISO格式
          if (dateStr.indexOf('T') === -1) {
            // 替换空格为T，确保格式正确
            dateStr = dateStr.replace(/\s+/g, 'T');
          }
          // 标准化日期格式
          date = new Date(dateStr);
        } else {
          date = new Date(dateStr);
        }
        
        // 检查日期是否有效
        if (isNaN(date.getTime())) {
          console.warn('无效的日期格式:', dateStr);
          return dateStr; // 返回原始字符串
        }
        
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        });
      } catch (error) {
        console.error('日期格式化错误:', error, dateStr);
        return dateStr; // 出错时返回原始字符串
      }
    },
    
    /**
     * 格式化日期
     * @param {string} dateStr - 日期字符串
     * @returns {string} - 格式化后的日期
     */
    formatDate(dateStr) {
      if (!dateStr) return '';
      
      try {
        // 处理多种可能的日期格式
        let date;
        if (typeof dateStr === 'string') {
          // 如果是普通的日期时间字符串格式(不含T)，先标准化为ISO格式
          if (dateStr.indexOf('T') === -1) {
            // 替换空格为T，确保格式正确
            dateStr = dateStr.replace(/\s+/g, 'T');
          }
          // 标准化日期格式
          date = new Date(dateStr);
        } else {
          date = new Date(dateStr);
        }
        
        // 检查日期是否有效
        if (isNaN(date.getTime())) {
          console.warn('无效的日期格式:', dateStr);
          return dateStr; // 返回原始字符串
        }
        
        return date.toLocaleDateString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit'
        });
      } catch (error) {
        console.error('日期格式化错误:', error, dateStr);
        return dateStr; // 出错时返回原始字符串
      }
    }
  }
};
</script>

<style scoped>
.announcement-detail-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.loading-container {
  padding: 40px 0;
}

.detail-card, .related-card {
  margin-bottom: 20px;
}

.announcement-header {
  margin-bottom: 20px;
}

.announcement-title {
  display: flex;
  align-items: center;
  font-size: 22px;
  margin-bottom: 15px;
  line-height: 1.4;
}

.announcement-title .el-tag {
  margin-right: 10px;
}

.announcement-meta {
  display: flex;
  flex-wrap: wrap;
  margin-top: 15px;
}

.meta-item {
  display: flex;
  align-items: center;
  margin-right: 20px;
  margin-bottom: 10px;
  color: #606266;
  font-size: 14px;
}

.meta-item i {
  margin-right: 5px;
  color: #909399;
}

.announcement-content {
  padding: 10px 0;
  line-height: 1.8;
}

.content-paragraph {
  margin-bottom: 15px;
  font-size: 15px;
  color: #303133;
  text-indent: 2em;
}

.announcement-actions {
  margin-top: 30px;
  text-align: center;
}

.related-header {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
}

.related-header i {
  margin-right: 8px;
  color: #409EFF;
}

.related-list {
  padding-top: 10px;
}

.related-item {
  padding: 12px;
  border-bottom: 1px solid #EBEEF5;
  cursor: pointer;
  transition: all 0.3s;
}

.related-item:hover {
  background-color: #F5F7FA;
}

.related-item:last-child {
  border-bottom: none;
}

.related-title {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.related-title span {
  margin-left: 5px;
  font-size: 15px;
  color: #303133;
}

.related-meta {
  display: flex;
  font-size: 12px;
  color: #909399;
}

.related-meta span {
  display: flex;
  align-items: center;
  margin-right: 15px;
}

.related-meta i {
  margin-right: 4px;
}

@media (max-width: 768px) {
  .announcement-meta {
    flex-direction: column;
  }
  
  .meta-item {
    margin-bottom: 8px;
  }
  
  .announcement-title {
    font-size: 20px;
  }
  
  .content-paragraph {
    font-size: 14px;
  }
}
</style> 